

#import "ImageController.h"
#import "TKCoverflowCoverView.h"
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
#import "MBProgressHUD.h"
#import "OriginImageViewController.h"
#import "OriginImageView.h"
#import "BlueArrowView.h"
#import "Setting.h"
#import "CoreDataManager.h"

@interface ImageController (Private)

- (void) loadMore;
- (void) refresh;

@end

@implementation ImageController

@synthesize coverflow,covers;
@synthesize originImageController;
@synthesize loadingPage;
@synthesize textView;
@synthesize showTextView;
@synthesize hud;

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void) didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}
- (void) viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}
- (void) dealloc {
	[coverflow release];
	[covers release];
    [_weiboDatas release];
    [originImageController release];
    [textView release];
    [hud release];
    
    [super dealloc];
}

- (void) loadView{
	
	CGRect r = [UIScreen mainScreen].bounds;
	r = CGRectApplyAffineTransform(r, CGAffineTransformMakeRotation(90 * M_PI / 180.));
	r.origin = CGPointZero;
	
	self.view = [[[UIView alloc] initWithFrame:r] autorelease];

	self.view.backgroundColor = [UIColor whiteColor];
	self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	
	
	r = self.view.bounds;
	r.size.height = 1000;
	
	coverflow = [[TKCoverflowView alloc] initWithFrame:self.view.bounds];
	coverflow.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	coverflow.coverflowDelegate = self;
	coverflow.dataSource = self;
	if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){
		coverflow.coverSpacing = 100;
		coverflow.coverSize = CGSizeMake(300, 300);
	}
	
	[self.view addSubview:coverflow];
    
    coverflow.arrowLoadingDelegate = self;
    coverflow.leftArrowLoadingCallback = @selector(refresh);
    coverflow.rightArrowLoadingCallback = @selector(loadMore);
    
    self.textView = [[[UITextView alloc] initWithFrame:CGRectMake(0, 327,
                                                                 320, 120)] autorelease];
    self.textView.scrollEnabled = NO;
    self.textView.editable = NO;
    self.textView.font = [UIFont systemFontOfSize:14];
    self.textView.textColor = [UIColor whiteColor];
    self.textView.backgroundColor = [UIColor blackColor];
    self.textView.alpha = 0.5;
    [self.view addSubview:self.textView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = self.textView.bounds;
    [button addTarget:self
               action:@selector(showTextview)
     forControlEvents:UIControlEventTouchUpInside];
    [self.textView addSubview:button];
    
    self.showTextView = NO;
}

- (void) showTextview {
    if (self.showTextView == YES) {
        self.textView.scrollEnabled = NO;
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.4f];
        
        CGRect frame = self.textView.frame;
        frame.origin.y += 80;
        self.textView.frame = frame;
        
        [UIView commitAnimations];
    }
    else {
        self.textView.scrollEnabled = YES;
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.4f];
        
        CGRect frame = self.textView.frame;
        frame.origin.y -= 80;
        self.textView.frame = frame;
        
        [UIView commitAnimations];
    }
    self.showTextView = !self.showTextView;
}

- (void) exit {
    [self dismissModalViewControllerAnimated:YES];
}

- (void) viewDidLoad {
    [super viewDidLoad];
      
    self.title = @"图片";
    
    covers = [[NSMutableArray alloc] init];
    _weiboDatas = [[NSMutableArray alloc] init];
    
    [self refresh];
}

- (void) coverflowView:(TKCoverflowView*)coverflowView coverAtIndexWasBroughtToFront:(int)index{
    if (index >= 0) {
        NSDictionary *weibodata = [_weiboDatas objectAtIndex:index];
        NSString *text = [weibodata objectForKey:@"text"];
//        self.title = text;
        self.textView.text = text;
    }
}

- (TKCoverflowCoverView*) coverflowView:(TKCoverflowView*)coverflowView coverAtIndex:(int)index{
	
	TKCoverflowCoverView *cover = [coverflowView dequeueReusableCoverView];

	if(cover == nil){
		BOOL phone = [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone;
		CGRect rect = phone ? CGRectMake(0, 0, 224, 300) : CGRectMake(0, 0, 300, 600);
        
		
		cover = [[TKCoverflowCoverView alloc] initWithFrame:rect]; // 224
		cover.baseline = 224;
		
	}
	cover.image = [covers objectAtIndex:index%[covers count]];
    
	return [cover autorelease];
	
}

- (void) coverflowView:(TKCoverflowView*)coverflowView coverAtIndexWasDoubleTapped:(int)index{
    
	
	TKCoverflowCoverView *cover = [coverflowView coverAtIndex:index];
	if(cover == nil) return;
    
	self.originImageController = [[[OriginImageViewController alloc] init] autorelease];
    self.originImageController.doubleTapDelegate = self;
    self.originImageController.doubleTapCallback = @selector(dismissController);
    [self.originImageController setImage:cover.image];
    
    self.originImageController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:self.originImageController animated:YES];
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.originImageController.view animated:YES];
    self.hud.mode = MBProgressHUDModeDeterminate;
    self.hud.labelText = @"Loading";
    
    NSDictionary *weibodata = [_weiboDatas objectAtIndex:index];
    NSString *originImageURL = [weibodata objectForKey:@"originImageURL"];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:originImageURL]];
    request.delegate = self;
    request.downloadProgressDelegate = self.hud;
    
    if ([originImageURL hasSuffix:@".gif"]) {
        request.didFinishSelector = @selector(originGifFinish:);
    }
    else {
        request.didFinishSelector = @selector(originImageFinish:);
    }
    
    [request startAsynchronous];
}

- (void) originImageFinish : (ASIHTTPRequest *)request {
    NSData *imageData = [request responseData];
    UIImage *image = [UIImage imageWithData:imageData];
    [self.originImageController setImage:image];
    [MBProgressHUD hideHUDForView:self.originImageController.view animated:YES];
    self.hud = nil;
}

- (void) originGifFinish : (ASIHTTPRequest *)request {
    NSData *imageData = [request responseData];
    [self.originImageController setGif:imageData];
    [MBProgressHUD hideHUDForView:self.originImageController.view animated:YES];
    self.hud = nil;
}

- (void) dismissController {
    [self.originImageController.toolbar removeFromSuperview];
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - Private Method

- (void) loadMore {
    if ([[SinaManager sharedManager].sinaWeiBo isUserLoggedin]) {
        self.loadingPage++;
        [[SinaManager sharedManager] getImageTimelineWithDelegate:self 
                                                             page:self.loadingPage];
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.mode = MBProgressHUDModeDeterminate;
        self.hud.labelText = @"Loading";
    }
}

- (void) refresh {
    if ([[SinaManager sharedManager].sinaWeiBo isUserLoggedin]) {
        self.loadingPage = 1;
        [_weiboDatas removeAllObjects];
        [covers removeAllObjects];
        
        [[SinaManager sharedManager] getImageTimelineWithDelegate:self 
                                                             page:self.loadingPage];
        
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.mode = MBProgressHUDModeDeterminate;
        self.hud.labelText = @"Loading";
    }
}

#pragma mark - Server

- (void)request:(WBRequest *)request didLoad:(id)result {
    NSDictionary *resultDic = (NSDictionary *)result;
//    NSLog(@"%@", resultDic);
    
    NSMutableArray *tempArray = [NSMutableArray array];
    
    for (NSDictionary *weibo in resultDic) {
        if ([weibo objectForKey:@"retweeted_status"] != nil) {
            NSDictionary *retweeted = [weibo objectForKey:@"retweeted_status"];
            NSString *text = [retweeted objectForKey:@"text"];
            
            NSString *smallImageURL = [retweeted objectForKey:@"thumbnail_pic"];
            NSString *middleImageURL = [retweeted objectForKey:@"bmiddle_pic"];
            NSString *originImageURL = [retweeted objectForKey:@"original_pic"];
            
            if (smallImageURL || middleImageURL || originImageURL) {
                NSDictionary *oneImageURLs = [NSDictionary dictionaryWithObjectsAndKeys:
                                              smallImageURL, @"smallImageURL",
                                              middleImageURL, @"middleImageURL",
                                              originImageURL, @"originImageURL",
                                              text, @"text",
                                              nil];
                [tempArray addObject:oneImageURLs];
            }
        }
        else {
            NSString *smallImageURL = [weibo objectForKey:@"thumbnail_pic"];
            NSString *middleImageURL = [weibo objectForKey:@"bmiddle_pic"];
            NSString *originImageURL = [weibo objectForKey:@"original_pic"];
            NSString *text = [weibo objectForKey:@"text"];
            
            if (smallImageURL || middleImageURL || originImageURL) {
                NSDictionary *oneImageURLs = [NSDictionary dictionaryWithObjectsAndKeys:
                                              smallImageURL, @"smallImageURL",
                                              middleImageURL, @"middleImageURL",
                                              originImageURL, @"originImageURL",
                                              text, @"text",
                                              nil];
                [tempArray addObject:oneImageURLs];
            }
        }
                
    }
    
    // load small images
    ASINetworkQueue *requestQueue = [ASINetworkQueue queue];
    requestQueue.delegate = self;
    requestQueue.shouldCancelAllRequestsOnFailure = NO;
    requestQueue.queueDidFinishSelector = @selector(loadAllSmallImageFinish:);
    requestQueue.requestDidFinishSelector = @selector(loadSmallImageFinish:);
    requestQueue.maxConcurrentOperationCount = 1;
    requestQueue.downloadProgressDelegate = self.hud;
    
    NSString *imageURLKey;
    Setting *setting = (Setting *)[[CoreDataManager sharedManager] getObjectOfClass:[Setting class]];
    if ([setting.network intValue] == 0) {
        imageURLKey = @"smallImageURL";
    }
    else if ([setting.network intValue] == 1) {
        imageURLKey = @"middleImageURL";
    }
    else if ([setting.network intValue] == 2) {
        imageURLKey = @"originImageURL";
    }
    
    for (NSDictionary *oneImageURLs in tempArray) {
        NSString *smallImageURL = [oneImageURLs objectForKey:imageURLKey];
        ASIHTTPRequest *smallImageRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:smallImageURL]];
        [requestQueue addOperation:smallImageRequest];
    }
    
    [requestQueue go];
    
    [_weiboDatas addObjectsFromArray:tempArray];
}

- (void) loadSmallImageFinish:(ASIHTTPRequest *) request {
    NSData *responseData = [request responseData];
    UIImage *image = [UIImage imageWithData:responseData];
    [covers addObject:image];
}

- (void) loadSmallImageFail:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    NSLog(@"%@", [error description]);
}

- (void) loadAllSmallImageFinish: (ASINetworkQueue *) queue {
    
    if (self.loadingPage > 1) {
        int currentIndex = coverflow.currentIndex;
        [coverflow setNumberOfCovers:[covers count]];
        coverflow.currentIndex = currentIndex;
    }
    else {
        [coverflow setNumberOfCovers:[covers count]];
    }
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    self.hud = nil;
    
    BlueArrowView *blueArrow = [[[BlueArrowView alloc] initWithFrame:CGRectMake(300, 5, 10, 10)] autorelease];
    [self.textView addSubview:blueArrow];
}
@end